package org.ala.tcp_feign_server.context.executor;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.ala.tcp_feign_common.logs.LoggerFactory;
import org.ala.tcp_feign_common.utils.MethodUrlUtils;
import org.slf4j.Logger;
import org.springframework.util.StringUtils;

/**
 * method - bean mapper
 * <p>	持有方法url - method的映射，url必须本jvm唯一
 * <p>	当有biz消息进来时，用改映射找到执行的bean和method，通过反射调用
 *
 * @author 骆毅(ala)
 * @date 2024年4月20日
 */
public class TcpFeignServerExecutorMapper {
	
	
	static Logger log = LoggerFactory.getLogger("tcp-feign", "server");

	
	/**
	 * 方法url和MethodMap
	 * <p>	初始化完成后才会开启netty，这里直接hashmap
	 */
	protected Map<String, TcpFeignServerExecutor> executorMapper = new HashMap<>();
	
	
	/**
	 * 根据url找到executor
	 */
	public TcpFeignServerExecutor getExecutor(String url) {
		return executorMapper.get(url);
	}
	
	
	/**
	 * 追加executor
	 */
	public void appendExecutor(Object bean, Method method, String path) {
		//	拿方法上的url，如果拿不到则放弃该方法
		String methodUrl = MethodUrlUtils.findUrl(method);
		if (StringUtils.isEmpty(methodUrl)) {return;}
		
		if (!methodUrl.startsWith("/")) {methodUrl = "/" + methodUrl;}
		if (!methodUrl.endsWith("/")) {methodUrl = methodUrl + "/";}
		
		String url = path + methodUrl;
		if (executorMapper.containsKey(url)) {
			throw new RuntimeException("url重复 url:" + url);
		}
		
		executorMapper.put(url, new TcpFeignServerExecutor(bean, method, url));
		
		log.info("[TcpFeignServerExecutorMapper appendExecutor] 注册MethodMapper url:" + url + " beanClass:" + bean.getClass().getName() + " method:" + method.getName());
	}
	
	
}
